package com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues

import android.content.Intent
import android.os.Handler
import android.text.Html
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGenerateDialog.DialogTempletQuesTypeChoose
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGenerateDialog.DialogThemeTypeChoose
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceDXT.QuesReplaceFragmentDxt
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceFHXZ.QuesReplaceFragmentFhxz
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceGCT.QuesReplaceFragmentGct
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceJDT.QuesReplaceFragmentJdt
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplacePPT.QuesReplaceFragmentPpt
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceTKT.QuesReplaceFragmentTkt
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceWXXZ.QuesReplaceFragmentWxxz
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceXZT.QuesReplaceFragmentXzt
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceYDPP.QuesReplaceFragmentYdpp
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceZHT.QuesReplaceFragmentZht
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReplaceQues.aibkQuesReplaceZW.QuesReplaceFragmentZw
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkReviewTestPaper.AibkTestPaperReviewActvity
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.MyRefreshFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TestPaperReplaceQuesInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TypeThemeInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import kotlinx.android.synthetic.main.aibk_activity_testpaper_replace_question.*
import kotlinx.android.synthetic.main.aibk_activity_testpaper_replace_question.SBtnBack
import kotlinx.android.synthetic.main.aibk_include_loading_refresh.*
import org.koin.androidx.viewmodel.ext.android.viewModel

class AibkTestPaperReplaceQuesActivity : KBaseActivity(), View.OnClickListener {

    private var originalQuesId:String = ""
    private var paperId = ""
    private var paperType = 0
    private var stuId = ""
    private var typeNo = ""
    private var genreId = 0
    private var specialFeature = ""
    private var itemNum = 0
    private var mFilterId = ""
    private var sFilterId = ""
    private var importKlgList: ArrayList<String>? = null
    private var mainKlgList: ArrayList<String>? = null
    private var themeKlgList: ArrayList<String> = ArrayList()
    private var isTheme = false
    private var theme = ""
    private var startIndex = 0

    companion object {
        fun launch(activity: AppCompatActivity,
                   originalQuesId:String,
                   paperId:String,
                   paperType:Int,
                   stuId: String,
                   typeNo: String,
                   genreId: Int,
                   specialFeature: String,
                   itemNum: Int,
                   mFilterId: String,
                   sFilterId: String,
                   importKlgList: ArrayList<String>,
                   mainKlgList: ArrayList<String>,
                   isTheme: Boolean,
                   theme:String,
                   startIndex: Int) {
            val intent = Intent(activity, AibkTestPaperReplaceQuesActivity::class.java)
            intent.putExtra("OriginalQuesID", originalQuesId)
            intent.putExtra("PaperID", paperId)
            intent.putExtra("PaperType", paperType)
            intent.putExtra("StuID", stuId)
            intent.putExtra("TypeNo", typeNo)
            intent.putExtra("GenreID", genreId)
            intent.putExtra("SpecialFeature", specialFeature)
            intent.putExtra("ItemNum", itemNum)
            intent.putExtra("MFilterID", mFilterId)
            intent.putExtra("SFilterID", sFilterId)
            intent.putStringArrayListExtra("ImportKlgList", importKlgList)
            intent.putStringArrayListExtra("MainKlgList", mainKlgList)
            intent.putExtra("IsTheme", isTheme)
            intent.putExtra("Theme", theme)
            intent.putExtra("StartIndex", startIndex)
            activity.startActivityForResult(intent, 1)
        }
    }

    private val mViewModel: MarkViewModel by viewModel()
    private var typeThemeInfor: TypeThemeInfor? = null
    private var testPaperReplaceQuesInfor: TestPaperReplaceQuesInfor? = null
    private var fragmentList: MutableList<Fragment>? = ArrayList()
    private var vpQuesPosition = 0

    override fun setLayout(): Int {
        return R.layout.aibk_activity_testpaper_replace_question
    }

    override fun initView() {
        SBtnBack.setOnClickListener(this)
        TvAnotherQues.setOnClickListener(this)
        TvSelectQues.setOnClickListener(this)
        if(isTheme){
            LlThemeView.visibility = View.VISIBLE
            BtnChangeTheme.setOnClickListener(this)
        }else{
            LlThemeView.visibility = View.GONE
        }
    }

    override fun initData() {
        originalQuesId = intent.getStringExtra("OriginalQuesID")
        paperId = intent.getStringExtra("PaperID")
        paperType = intent.getIntExtra("PaperType",0)
        stuId = intent.getStringExtra("StuID")
        typeNo = intent.getStringExtra("TypeNo")
        genreId = intent.getIntExtra("GenreID", 0)
        specialFeature = intent.getStringExtra("SpecialFeature")
        itemNum = intent.getIntExtra("ItemNum", 0)
        mFilterId = intent.getStringExtra("MFilterID")
        sFilterId = intent.getStringExtra("SFilterID")
        importKlgList = intent.getStringArrayListExtra("ImportKlgList")
        mainKlgList = intent.getStringArrayListExtra("MainKlgList")
        isTheme = intent.getBooleanExtra("IsTheme", false)
        theme = intent.getStringExtra("Theme")
        startIndex = intent.getIntExtra("StartIndex", 0)
        Log.e("initData", "===importKlgList=======$importKlgList")
        Log.e("initData", "===mainKlgList=======$mainKlgList")

        if(isTheme) {
            mViewModel.getTypeThemeList(
                    typeNo,
                    genreId)
                    .doOnSubscribe {
                        RlGifLoading.visibility = View.VISIBLE
                        RlQuesInfor.visibility = View.GONE
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            typeThemeInfor = it.data

                            val typeThemeListSize = typeThemeInfor!!.size
                            for (i in 0 until typeThemeListSize) {
                                val chineseName = typeThemeInfor!![i].ChineseName
                                if(chineseName == theme) {
                                    val uniqueCode = typeThemeInfor!![i].UniqueCode
                                    themeKlgList.add(uniqueCode)
                                }
                            }

                            getReplaceQuesInfoAndShowView(false)

                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 1000)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 1000)
                    })
        }else{
            getReplaceQuesInfoAndShowView(true)
        }
    }

    private fun getReplaceQuesInfoAndShowView(isNeedLoading: Boolean) {
        mViewModel.getReplaceQuesInfo_1v1(
                stuId,
                typeNo,
                genreId,
                specialFeature,
                itemNum,
                mFilterId,
                sFilterId,
                importKlgList!!,
                mainKlgList!!,
                themeKlgList,
                isTheme,
                startIndex)
                .doOnSubscribe {
                    if(isNeedLoading){
                        RlGifLoading.visibility = View.VISIBLE
                        RlQuesInfor.visibility = View.GONE
                    }
                }.bindLifeCycle(this)
                .subscribe({
                    if (it.code == 1) {
                        RlGifLoading.visibility = View.GONE
                        testPaperReplaceQuesInfor = it.data

                        val replaceQuesListSize = testPaperReplaceQuesInfor!!.size
                        outLoop@ for (i in 0 until replaceQuesListSize) {
                            val quesId = testPaperReplaceQuesInfor!![i].QuesID
                            if (sFilterId.contains(quesId)) {//若当前试题ID在过滤列表中则清空过滤列表，否则继续增加过滤项
                                sFilterId = ""
                                break@outLoop
                            } else {
                                if (sFilterId.isEmpty()) {
                                    sFilterId = quesId
                                } else {
                                    sFilterId = "$sFilterId|$quesId"
                                }
                            }
                        }

                        showReplaceQuesView(testPaperReplaceQuesInfor!!)//加载可用于替换的试题界面
                    } else {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    }
                }, {
                    MyToast.showToast(it.message)
                    Handler().postDelayed({
                        finish()
                    }, 500)
                })
    }

    private fun showReplaceQuesView(testPaperReplaceQuesInfor: TestPaperReplaceQuesInfor) {

        if(theme.isEmpty()){
            TvThemeName.text = "无"
        }else {
            TvThemeName.text = theme
        }

        //加载试题,显示试卷作答情况
        fragmentList?.clear()
        var replaceQuesListSize = testPaperReplaceQuesInfor.size
        for (i in 0 until replaceQuesListSize) {
            if (typeNo == "A") {
                val mFragment = QuesReplaceFragmentDxt(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "C") {
                val mFragment = QuesReplaceFragmentWxxz(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "L" ||typeNo == "E" || typeNo == "F" || typeNo == "D") {//听力选择，听力判断，阅读选择
                val mFragment = QuesReplaceFragmentXzt(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "k") {
                val mFragment = QuesReplaceFragmentZht(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "H") {
                val mFragment = QuesReplaceFragmentFhxz(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            }else if (typeNo == "f") {
                val mFragment = QuesReplaceFragmentZw(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "N" || typeNo == "S") { //N:普通填空题  S：听力填空题
                val mFragment = QuesReplaceFragmentTkt(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "Q" || typeNo == "b" || typeNo == "d"
                    || typeNo == "X" || typeNo == "g" || typeNo == "V"
                    || typeNo == "G") {//Q:阅读填空,X:阅读简答,G:听力简答,
                val mFragment = QuesReplaceFragmentJdt(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "x" || typeNo == "m") {//x:听力匹配,m:普通匹配题
                val mFragment = QuesReplaceFragmentPpt(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "U") {
                val mFragment = QuesReplaceFragmentGct(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            } else if (typeNo == "P") {
                val mFragment = QuesReplaceFragmentYdpp(this, testPaperReplaceQuesInfor, i)
                (fragmentList as ArrayList<Fragment>).add(mFragment)
            }
        }

        val mAdapter = MyRefreshFragmentPagerAdapter(supportFragmentManager, fragmentList as ArrayList<Fragment>)
        VpReplaceQues.adapter = mAdapter

        //处理viewpager滑动事件
        VpReplaceQues.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                TvThemeName.text = testPaperReplaceQuesInfor[position].Theme

                vpQuesPosition = position
                showQuesIndexInfor(position)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        showQuesIndexInfor(0)
    }

    private fun showQuesIndexInfor(currentIndex:Int){

        if(RlQuesInfor.visibility == View.GONE) {
            RlQuesInfor.visibility = View.VISIBLE
        }

        val replaceQuesListSize = testPaperReplaceQuesInfor!!.size
        TvAnotherQuesIndexInfor.text = Html.fromHtml(resources.getString(R.string.aibk_replace_question_index_infor,
                currentIndex+1,replaceQuesListSize ))
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.SBtnBack -> {
                toolPauseAudio()
                finish()
            }
            R.id.TvAnotherQues ->{
                toolPauseAudio()
                //换一批
                getReplaceQuesInfoAndShowView(true)
            }
            R.id.TvSelectQues ->{
                toolPauseAudio()
                val currentQuesId = testPaperReplaceQuesInfor!![vpQuesPosition].QuesID
                //选用
                mViewModel.saveReplacedQues(
                        currentQuesId,
                        originalQuesId,
                        paperId,
                        paperType)
                        .doOnSubscribe {
                            startLoad()
                        }.bindLifeCycle(this)
                        .subscribe({
                            if (it.code == 1) {
                                stopLoad()
                                MyToast.showToast(it.message)
                                if(it.data){
                                    //替换成功后退出试卷替换页，并刷新新组的试卷
                                    backToAnswerSheetActivity()
                                }
                            } else {
                                MyToast.showToast(it.message)
                            }
                        }, {
                            MyToast.showToast(it.message)
                        })
            }
            R.id.BtnChangeTheme ->{
                val currentThemeName = TvThemeName.text.toString()
                //弹出切换主题弹窗
                val dialogThemeTypeChoose = DialogThemeTypeChoose(
                        this@AibkTestPaperReplaceQuesActivity,
                        this@AibkTestPaperReplaceQuesActivity,
                        typeThemeInfor!!,
                        currentThemeName)
                dialogThemeTypeChoose.setClickThemeListener(object :DialogThemeTypeChoose.OnClickThemeListener{

                    override fun onClickSure(themType: String) {
                        theme = themType
                        TvThemeName.text = themType

                        themeKlgList.clear()
                        val typeThemeListSize = typeThemeInfor!!.size
                        for (i in 0 until typeThemeListSize) {
                            val chineseName = typeThemeInfor!![i].ChineseName
                            if(chineseName == theme) {
                                val uniqueCode = typeThemeInfor!![i].UniqueCode
                                themeKlgList.add(uniqueCode)
                            }
                        }
                    }

                })
                dialogThemeTypeChoose.show()

            }
        }
    }

    //返回操作，并将需要的信息传递给上一个界面
    private fun backToAnswerSheetActivity() {
        val intent = Intent(this@AibkTestPaperReplaceQuesActivity, AibkTestPaperReviewActvity::class.java)
//        intent.putExtra("TypeListPosition", typeListPosition)
        setResult(303, intent)
        finish()
    }

    override fun onPause() {
        super.onPause()
        toolPauseAudio()
    }

    //暂停一切音频播放
    private fun toolPauseAudio() {
        if (testPaperReplaceQuesInfor != null) {
            var typeNo = testPaperReplaceQuesInfor!![vpQuesPosition].TypeNo
            if (typeNo == "x") {//x:听力匹配
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentPpt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "L" ||typeNo == "E" || typeNo == "F") {//听力选择，听力判断
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentXzt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "G") {//G:听力简答,
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentJdt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "S") { // S：听力填空题
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentTkt
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "f") {
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentZw
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            } else if (typeNo == "H") {
                val fragment = fragmentList!![vpQuesPosition] as QuesReplaceFragmentFhxz
                fragment.pauseAudio()
                fragment.pauseChildAudio()
                fragment.audioTrackerStop()
            }
        }
    }

}